package com.kinyx.framework.constraints;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.util.XHashMap;
import javax.validation.Constraint;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

import com.kinyx.framework.constraints.ID.Validator;
import com.kinyx.framework.file.KPropertiesReader;
import com.kinyx.framework.utils.KMatcherUtils;
import com.kinyx.framework.utils.KStringUtils;

/**
 * 主键验证注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = Validator.class)
public @interface ID {

	public static final String REGEX = KPropertiesReader.getStringValue(Configs.PROPERTIES, ID.class.getSimpleName(), "[a-zA-Z0-9]{${size}}");

	String message() default "";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};

	int size() default 32;

	class Validator extends RegexMatchValidator<ID> {

		private int size;

		@Override
		public void initialize(final ID annotation) { this.size = annotation.size(); }

		@Override
		protected boolean validate(final String value, final ConstraintValidatorContext context) {
			return KMatcherUtils.matches(value, KStringUtils.replaceEL(REGEX, new XHashMap<String, Object>().xPut("size", this.size)));
		}

	}

}
